package com.mike.zookeeper;

import com.alibaba.fastjson.JSON;
import org.apache.curator.RetryPolicy;
import org.apache.curator.RetrySleeper;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Hello world!
 */
public class App {

    static ReentrantLock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();
    public static void main(String[] args) throws Exception {

//创建zookeeper的客户端

//        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//
//        CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
//
//        client.start();
//
////创建分布式锁, 锁空间的根节点路径为/curator/lock
//
//        InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
//
//        mutex.acquire();
//
////获得了锁, 进行业务流程
//
//        System.out.println("Enter mutex");
//
////完成业务流程, 释放锁
//
//        mutex.release();

//关闭客户端

//        client.close();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock.lock();
                    TimeUnit.SECONDS.sleep(6);
                    condition.signalAll();
                    lock.unlock();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

//        while (true){
            lock.lock();
            condition.await();
            System.out.println("release");
            lock.unlock();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.lock();
                    System.out.println("jinlaila");
                }
            }).start();

//        }



    }



}
